<?php

namespace App\Services\Draw\DrawObject;


use App\Enums\AppJumpEnum;
use App\Exceptions\BasicException;
use App\Jobs\QiPao\Draw\StellarDrawStatisticsJob;
use App\Models\MainDB\Gift;
use App\Models\MainDB\GiftBackpack;
use App\Repositories\GiftRepository;
use App\Repositories\Stellar\StellarPropsRepository;
use App\Services\Draw\DrawConst\CacheKey;
use App\Services\Draw\Enum\DrawEnum;
use App\Services\Draw\PoolGroupObject\StellarIndependentPoolGroup;
use App\Services\Draw\PoolGroupObject\StellarPublicPoolGroup;
use App\Services\Tools\PushChatService;
use App\Services\Tools\PushService;
use App\Services\Tools\RedisService;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Enums\RedisKeyEnum;

/**
 * 幸运神灯抽奖实体
 * @author wrh
 */
class Stellar extends Draw
{
    protected $isDrawCriticalGift = false;
    protected $cachePrefix = 'stellar:';
    protected $privateKey = 'stellar';
    protected $balanceNotEnoughMsg = '神灯数量不足';
    protected $drawLockKey = "draw:stellar:lock_";
    protected $isDrawAccumulate = false; //是否做抽奖计数累计逻辑

    public function __construct()
    {
        parent::__construct();
        $this->redisObject               = app('redis')->connection('game');
        $this->poolConfigModel           = app('model_stellar_pool_config');
        $this->poolUserModel             = app('model_stellar_pool_user');
        $this->poolModel                 = app('model_stellar_pool');
        $this->poolPrizeModel            = app('model_stellar_pool_prize');
        $this->poolGroupModel            = app('model_stellar_pool_group');
        $this->giftTemplateModel         = app('model_stellar_gift_template');
        $this->poolTemplateModel         = app('model_stellar_pool_template');
        $this->poolDrawModel             = app('model_stellar_pool_draw');
        $this->poolDrawRecordModel       = app('model_stellar_pool_draw_record');
        $this->poolIndependentModel      = app('model_stellar_pool_independent');
        $this->poolIndependentPrizeModel = app('model_stellar_pool_independent_prize');
        $this->appointGiftModel = app('model_stellar_appoint_gift');

        $this->checkRecordModel = app('model_stellar_draw_check_record');
        $this->addPoolAccountRecordModel = app('model_stellar_draw_add_pool_account_record');
        $this->addPoolRepo = app('repo_add_pool_stellar');

        $this->independentPoolGroup = new StellarIndependentPoolGroup($this->redisObject);
        $this->publicPoolGroup      = new StellarPublicPoolGroup($this->redisObject);
    }

    public function isNovice($user, $poolConfig)
    {
        return $user->input_week <= $poolConfig->novice_coin;
    }

    // 添加抽奖记录
    public function addDrawRecord($user, $poolGroup, array $drawIOPut, Collection $gifts, $criticalGift, array $drawPrizes, int $drawCount, int $drawPrizesCount)
    {
        //并发处理
        if ($poolGroup->group_id == 0) {
            $poolGroup->group_id = key($drawPrizes);
        }


        $drawData = [
            "user_id"    => $user->user_id,
            "group_id"   => $poolGroup->group_id,
            "tag"        => $poolGroup->tag,
            "count"      => $drawCount,
            "gift_count" => $drawPrizesCount,
            "input"      => $drawIOPut['input'],
            "output"     => $drawIOPut['output'],
        ];

        $poolDrawId = $this->poolDrawModel->createDataGetId($drawData);
        if (empty($poolDrawId)) {
            throw new BasicException(-1, '抽奖记录保存错误');
        }
        $drawPrizesRecord = [];
        foreach ($drawPrizes as $groupId => $groupPrize) {
            foreach ($groupPrize as $prizeId => $prizeCount) {
                $gift               = $gifts->where('gift_template_id', $prizeId)->first();
                $drawPrizesRecord[] = ['user_id' => $user->user_id, 'draw_id' => $poolDrawId, 'group_id' => $groupId,
                    'gift_id' => $gift->id, 'gift_price' => $gift->price, 'count' => $prizeCount, 'gift_type' => $gift->type];
            }
        }
        if (!empty($criticalGift)) {
            $drawPrizesRecord[] = ['user_id' => $user->user_id, 'draw_id' => $poolDrawId, 'group_id' => 0,
                'gift_id' => $criticalGift['id'], 'gift_price' => 0, 'count' => $criticalGift['count'], 'gift_type' => DrawEnum::PROP_GIFT_TYPE];


        }

        $this->poolDrawRecordModel->insert($drawPrizesRecord);
        return $drawData;
    }

    public function getDrawJob($poolGroup, $user, $jobData)
    {
        return new StellarDrawStatisticsJob($poolGroup, $user, $jobData, $this->cachePrefix);

    }

    public function getGiftList(array $drawPrizes)
    {
        //根据模板礼物ID获取礼物ID
        $templateGiftIds = [];
        $giftPrizes      = [];
        foreach ($drawPrizes as $groupId => $groupPrize) {
            foreach ($groupPrize as $prizeId => $prizeCount) {
                $templateGiftIds[] = $prizeId;
                if (isset($giftPrizes[$prizeId])) {
                    $giftPrizes[$prizeId] += $prizeCount;
                } else {
                    $giftPrizes[$prizeId] = $prizeCount;
                }
            }
        }

        $templateGiftList   = $this->giftTemplateModel->getGiftListByIds($templateGiftIds, ['id', 'type', 'gift_id']);
        $templateGiftWithId = $templateGiftList->where('type', DrawEnum::NORMAL_GIFT_TYPE)->KeyBy('gift_id');
        //$templatePropWithId = $templateGiftList->where('type', DrawEnum::PROP_GIFT_TYPE)->KeyBy('gift_id');
        $giftInfoList = (new GiftRepository())->giftsByIds($templateGiftWithId->keys()); // 抽中礼物信息

        foreach ($giftInfoList as $giftInfo) {
            $giftInfo->gift_template_id = $templateGiftWithId[$giftInfo['id']] ? $templateGiftWithId[$giftInfo['id']]['id'] : 0;
            $giftInfo->count            = $giftPrizes[$giftInfo->gift_template_id] ?? 0;
            $giftInfo->type             = DrawEnum::NORMAL_GIFT_TYPE;
        }

//        if (!empty($templatePropWithId)) {
//            //查询道具价格
//            $propGiftList = app('model_props')->select('id', 'name', 'prope_icon as picture', 'price')->whereIn('id', $templatePropWithId->keys())->where('is_delete', 0)->get();
//            if ($propGiftList->isNotEmpty()) {
//                $propGiftListWithId = $propGiftList->KeyBy('id');
//                foreach ($templatePropWithId as $templateId => $propGift) {
//                    $propGiftInfo                   = $propGiftListWithId[$propGift['gift_id']];
//                    $propGiftInfo->gift_template_id = $propGift->id;
//                    $propGiftInfo->count            = $giftPrizes[$propGift->id] ?? 0;
//                    $propGiftInfo->type             = DrawEnum::PROP_GIFT_TYPE;
//                    $giftInfoList[]                 = $propGiftInfo;
//                }
//            }
//        }

        return $giftInfoList;
    }

    public function getNotifyGiftList($count)
    {
        $cacheNotifyRecordList = $this->redisObject->get($this->cachePrefix . "notifyRecordList:" . $count);
        if (!empty($cacheNotifyRecordList)) {
            $notifyRecordList = json_decode($cacheNotifyRecordList, true);
        }
        if (empty($notifyRecordList)) {
            $notifyRecordList = parent::getNotifyGiftList($count);
            $this->redisObject->setex($this->cachePrefix . "notifyRecordList:" . $count, 60, json_encode($notifyRecordList));
        }

        return $notifyRecordList;
    }


//    public function pushv1($user, array $notifyPushData, array $broadcastPushData, array $extraPushData)
//    {
//        try {
//            $userChatLabel = RedisService::getUserChatLabel($user->user_id);
//            //$levelInfo = $this->levelModel->one(['level' => $user->level]);
//
//            foreach ($notifyPushData as $value) {
//                // (new PushChatService())->lotteryStellarNew($userChatLabel, $value);
//            }
//
//
//            foreach ($notifyPushData as $value) {
//                (new PushChatService())->lotteryStellarNew($userChatLabel, $value);
//            }
//
//            (new PushService())->lotteryStellar($broadcastPushData, $userChatLabel);
//        } catch (\Exception $e) {
//            return false;
//        }
//        return true;
//    }

    /**
     * @param $user
     * @param array $notifyPushData
     * @param array $broadcastPushData
     * @param array $extraPushData
     * @throws \Exception
     */
    public function push($user, array $notifyPushData, array $broadcastPushData, array $extraPushData)
    {
        $userChatLabel = RedisService::getUserChatLabel($user->user_id);
        $uni_key = uniqidReal();
        $getMillisecond = getMillisecond();
        $PushService = new PushService();
        // /幸运票品
        $notifyPush = [];
        if(!empty($notifyPushData)){
            $ext_data = $userChatLabel;
            $txt = "<font color='#75CEFE'>在幸运神灯中获得了</font>";

            foreach ($notifyPushData as $key => $value) {
                $txt .= '<font color="#FDA94E">价值' . $value->price . '</font>';
                $txt .= '<font color="#75CEFE">金币的</font>';
                //$txt .= "<font color='#22C4F1'>的 </font>";
                $txt .= '<font color="#4DDB96">' . $value->name . ' x ' . $value->count . '.'.'</font>';
            }

            $ext_data['type'] = PushService::GAME_PUSH_STATUS;
            $ext_data['action'] = 1;
            $ext_data['show_area'] = [
                PushChatService::AREA_LUCKY,
                PushChatService::AREA_ALL,
            ];
            $ext_data['show_label_id'] = [
                PushChatService::AREA_LUCKY,
            ];
            $ext_data['bg_type'] = $this->privateKey;
            $notifyPush = [
                'content' => $txt,
                'uni_key' => $uni_key,
                'extra' => $ext_data
            ];
        }
        $broadcastPush = [];
        if(!empty($broadcastPushData)){
            $txt = "<font color='#FFEB66'>" . mb_substr($userChatLabel['nickname'], 0, 1) . "**</font><font color='#FFFFFF'> 获得了价值 </font>";
            $txt_extra = [];
            foreach ($broadcastPushData as $gift) {
                $txt_extra [] = [
                    'text' => $txt . "<font color='#FFEB66'>" . $gift->price . "金币的</font>" . "<font color='#73E8FF'>" . $gift->name . "</font><font color='#FFFFFF'>X" . $gift->count . "</font>",
                    'picture' => $gift->picture,
                ];
            }
            $broadcastPush = [
                'uni_key' => $uni_key,
                'time' => $getMillisecond,
                'msg'  => $txt_extra,
                'special' => RedisService::getBroadcastSpecial($user->user_id),
                'bg_type' => $this->privateKey,
                'show_grade' => $this->showBroadcastGrade(),
            ];
        }

        $PushService->publicGamePush($notifyPush,$broadcastPush,[],[],$uni_key,$getMillisecond);

    }

    public function getUserQueuePool($userId, int $count)
    {
        return null;

    }

//    public function getUserPool()
//    {
//
//    }

//
//    /**
//     * @param int $userId
//     * @param int $count
//     */
//    public function swap(int $userId, int $count)
//    {
//
//    }


}
